import React, { useEffect, useState, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { getTimetable, editTimetableEntry, updateEntry } from '../features/timetable/timetableSlice';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, TextField, CircularProgress, Typography, Alert } from '@mui/material';

const Timetable = () => {
    const dispatch = useDispatch();
    const timetable = useSelector((state) => state.timetable.entries);
    const status = useSelector((state) => state.timetable.status);
    const error = useSelector((state) => state.timetable.error);
    const ws = useRef(null);

    useEffect(() => {
        if (status === 'idle') {
            dispatch(getTimetable());
        }

        ws.current = new WebSocket('ws://localhost:8000/ws/timetable/');
        ws.current.onmessage = (event) => {
            const data = JSON.parse(event.data);
            dispatch(updateEntry(data));
        };

        return () => {
            ws.current.close();
        };
    }, [dispatch, status]);

    const handleInputChange = (id, field, value) => {
        const updatedEntry = timetable.find(entry => entry.id === id);
        const newEntry = { ...updatedEntry, [field]: value };

        // Отправляем обновление на сервер
        dispatch(editTimetableEntry({ id, entry: newEntry }));

        // Отправляем обновление через WebSocket
        ws.current.send(JSON.stringify(newEntry));
    };

    if (status === 'loading') {
        return <CircularProgress />;
    }

    if (status === 'failed') {
        return <Alert severity="error">Ошибка: {error}</Alert>;
    }

    return (
        <TableContainer component={Paper}>
            <Typography variant="h6" gutterBottom>
                Табель
            </Typography>
            <Table>
                <TableHead>
                    <TableRow>
                        <TableCell>Фамилия Имя Отчество</TableCell>
                        <TableCell>Модальность</TableCell>
                        <TableCell>Дополнительные модальности</TableCell>
                        <TableCell>Начало смены</TableCell>
                        <TableCell>Конец смены</TableCell>
                        <TableCell>Время перерыва (мин)</TableCell>
                        <TableCell>Отработанные часы</TableCell>
                    </TableRow>
                </TableHead>
                <TableBody>
                    {timetable.map((entry) => (
                        <TableRow key={entry.id}>
                            <TableCell>{entry.name}</TableCell>
                            <TableCell>{entry.modality}</TableCell>
                            <TableCell>{entry.additional_modalities}</TableCell>
                            <TableCell>
                                <TextField
                                    type="time"
                                    value={entry.shift_start}
                                    onChange={(e) => handleInputChange(entry.id, 'shift_start', e.target.value)}
                                    InputLabelProps={{ shrink: true }}
                                />
                            </TableCell>
                            <TableCell>
                                <TextField
                                    type="time"
                                    value={entry.shift_end}
                                    onChange={(e) => handleInputChange(entry.id, 'shift_end', e.target.value)}
                                    InputLabelProps={{ shrink: true }}
                                />
                            </TableCell>
                            <TableCell>
                                <TextField
                                    type="number"
                                    value={entry.break_time}
                                    onChange={(e) => handleInputChange(entry.id, 'break_time', e.target.value)}
                                    InputLabelProps={{ shrink: true }}
                                />
                            </TableCell>
                            <TableCell>
                                <TextField
                                    type="number"
                                    value={entry.worked_hours}
                                    onChange={(e) => handleInputChange(entry.id, 'worked_hours', e.target.value)}
                                    InputLabelProps={{ shrink: true }}
                                />
                            </TableCell>
                        </TableRow>
                    ))}
                </TableBody>
            </Table>
        </TableContainer>
    );
};

export default Timetable;
